var home = require("../../utils/util.js");
var url = home.home;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    active: 0,
    data: [], //列表
    show: false,
    show1: false, //分享弹出层
    show9: false, //海报
    loadImagePath: '',
    vipId: '',
    types: 1,
    vipJson:{},
    lqFlag:0,
    bgcolor: home.getKey('bgcolor'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  show1(e) {
    let id = e.currentTarget.dataset.id;
    let json = {};
    for (let i = 0; i < this.data.data.length; i++) {
      if (this.data.data[i].id == id) {
        json = this.data.data[i];
      }
    }
    home.setKey('posterName',json.cardName);
    json.shareId = json.id;
    this.setData({
      show1: true,
      vipId: e.currentTarget.dataset.id,
      vipJson: json,
    });
  },

  onShareAppMessage(){
    let json = this.data.vipJson;
    console.log(json)
    wx.request({
      url: url + 'app/shareVip',
      data:{
        storeId:home.getKey('storeId'),
        memberId:home.getKey('userId'),
        type:"2",
        shareVipId:json.id,
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认 
      },
      success:function (res) {
      }
    })
    return {
      title: json.cardName,
      //imageUrl: 'https://kyz.fbhkj.com/fubaihui/' + json.detailsUrl,
      imageUrl: 'https://kyz.fbhkj.com//' + json.detailsUrl,
      path: '/shop/guest/info?type=4&id='+json.id // 路径，传递参数到指定页面。
    }
  },

  //生成小程序码
  getQrcode(shareVipId){
    wx.request({
      url: url + 'app/shareVip',
      data:{
        storeId:home.getKey('storeId'),
        memberId:home.getKey('userId'),
        type:"1",
        shareVipId:shareVipId,
        page:'shop/guest/info',
        env_version:'release',
      },
      responseType: 'arraybuffer',
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认 
      },
      success:function (res) {
        let file = wx.getFileSystemManager();
        let filePath = wx.env.USER_DATA_PATH + '/qrcode.png';
        file.writeFile({
          filePath:filePath,
          data:wx.arrayBufferToBase64(res.data),
          encoding: 'base64',
          success(rea){
            console.log(rea);
          }
        })
      }
    })
  },

  //关闭分享弹出层
  onClose() {
    this.setData({
      show1: false
    });
  },

  onChange(e) {
    let types = 1;
    if (e.detail.index == 1) {
      types = 2;
    } else if (e.detail.index == 2) {
      types = 6;
    }
    this.setData({
      active: e.detail.index,
      page: 1,
      data: [],
      types: types,
    });
    this.getGuestList();
  },

  //查询贵宾卡列表
  getGuestList() {
    let that = this;
    wx.request({
      url: url + 'app/getMemberVipList',
      data: {
        storeId: home.getKey('storeId'),
        memberId: home.getKey('userId'),
        pageNo: that.data.page,
        type: that.data.types,
      },
      method: 'GET',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          let data = that.data.result;
          if (that.data.page == 1) {
            data = res.data.result;
          } else {
            for (let i = 0; i < res.data.result.length; i++) {
              data.push(res.data.result[i]);
            }
          }
          let show = false;
          if (data.length == 0) {
            show = true;
          }
          that.setData({
            data: data,
            show: show
          });
        } else {
          home.wxMessage('获取失败,请稍后再试', 'none');
        }
      }
    })
  },

  //领取贵宾卡
  lq(e) {
    let id = e.currentTarget.dataset.id;
    let that = this;
    let data = that.data.data;
    if(that.data.lqFlag == 1){
      home.wxMessage('不可重复领取', 'none');
      return;
    }
    this.data.lqFlag = 1;
    wx.request({
      url: url + 'app/receiveVip',
      data: {
        storeId: home.getKey('storeId'),
        memberId: home.getKey('userId'),
        toReceiveVipId: id,
      },
      method: 'POST',
      header: {
        "content-type": "application/json", // 默认
      },
      success: function (res) {
        if (res.data.code == 200) {
          if (res.data.result.payParams != null) {
            wx.requestPayment({
              "timeStamp": res.data.result.payParams.timeStamp,
              "nonceStr": res.data.result.payParams.nonceStr,
              "package": res.data.result.payParams.package_str,
              "signType": res.data.result.payParams.signType,
              "paySign": res.data.result.payParams.paySign,
              "success": function (res) {
                if (res.errMsg == 'requestPayment:ok') {
                  for (let i = 0; i < data.length; i++) {
                    if (data[i].id == id) {
                      data[i].shareNum = parseFloat(data[i].shareNum) - 1;
                    }
                  }
                  that.setData({
                    data: data
                  });
                  home.wxMessage('领取成功','success');
                  that.getGuestList();
                }
              },
              "fail": function (res) {
                wx.showToast({
                  title: '取消支付',
                  icon: 'none'
                });
                return false;
              },
              "complete": function (res) {}
            })
          } else {
            for (let i = 0; i < data.length; i++) {
              if (data[i].id == id) {
                data[i].shareNum = parseFloat(data[i].shareNum) - 1;
              }
            }
            that.setData({
              data: data
            });
            home.wxMessage('领取成功','success');
            that.getGuestList();
          }
        } else {
          home.wxMessage('领取失败','none');
        }
      }
    })
  },

  /**
   * 跳转领取贵宾卡页面
   */
  toInfo(e) {
    let id = e.currentTarget.dataset.id;
    let types = this.data.types;
    //type为1  不显示店铺贵宾卡信息
    //type为2  不显示店铺贵宾卡信息
    //type为3  显示店铺贵宾卡信息
    wx.navigateTo({
      url: './info?type=' + types + '&id=' + id,
    })
  },

  onClose2() {
    this.setData({
      show9: false
    });
  },

  hb() {
    this.getQrcode(this.data.vipJson.id);
    let that = this;
    setTimeout(function(){
      that.hb1();
    },1000);
  },

  hb1() {
    let storePhone = home.getKey('storePhone');
    let storeCity = home.getKey('storeCity');
    let storeName = home.getKey('storeName');
    let posterName = home.getKey('posterName');
    this.setData({
      show9: true,
      show1: false
    });
    let height = wx.getSystemInfoSync().windowHeight * 0.8;
    if (wx.getSystemInfoSync().windowHeight == 504) {
      height = wx.getSystemInfoSync().windowHeight - 40;
    }
    let width = wx.getSystemInfoSync().windowWidth - 40;
    this.setData({
      height: height,
      width: width
    })
    let that = this;
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr);
        ctx.fillRect(0, 0, width, 0);
        //绘制背景图
        wx.getImageInfo({
          src: "https://kyz.fbhkj.com/canvas_back.png",
          success: (res) => {
            let imageUrl = res.path // 图片临时地址
            let imageW = res.width
            let imageH = res.height
            let ratio = wx.getSystemInfoSync().pixelRatio // 获取比例

            // 1. 创建一个图片对象。支持在 2D Canvas 和 WebGL Canvas 下使用, 但不支持混用 2D 和 WebGL 的方法。
            let imageObj = canvas.createImage()
            // 2. 给创建的图片对象的src赋值
            imageObj.src = imageUrl
            let qrcodeImg = canvas.createImage();
            qrcodeImg.src = wx.env.USER_DATA_PATH + '/qrcode.png';
            // 3. 图片加载完之后触发
            imageObj.onload = () => {
              // 4. 绘制图片
              ctx.drawImage(imageObj, 0, 20, width, height);
              //绘制文本
              ctx.font = 'italic bold 30px Arial';
              ctx.fillStyle = 'white';
              ctx.textAlign = 'center';
              ctx.fillText(storeName, width / 2, height / 2 * 0.35);
              ctx.font = '12px Arial';
              ctx.fillStyle = '#fff';
              ctx.textAlign = 'center';
              ctx.fillText('电话:'+storePhone, width / 2, height / 2 * 0.53);
              ctx.font = '12px Arial';
              ctx.fillStyle = '#fff';
              ctx.textAlign = 'center';
              ctx.fillText('地址:'+storeCity, width / 2, height / 2 * 0.6);
              ctx.font = 'bold 26px Arial';
              ctx.fillStyle = '#D19C46';
              ctx.textAlign = 'center';

var chr =posterName.split("");//这个方法是将一个字符串分割成字符串数组
var temp = "";
var row = [];
for (var a = 0; a < chr.length; a++) {
  if (ctx.measureText(temp).width < 230) {
   temp += chr[a];
  }
  else {
   a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
   row.push(temp);
   temp = "";
  }
}
row.push(temp);
//如果数组长度大于2 则截取前两个
if (row.length > 2) {
  var rowCut = row.slice(0, 2);
  var rowPart = rowCut[1];
  var test = "";
  var empty = [];
  for (var a = 0; a < rowPart.length; a++) {
   if (ctx.measureText(test).width < 200) {
    test += rowPart[a];
   }
   else {
    break;
   }
  }
  empty.push(test);
  var group = empty[0] + "..."//这里只显示两行，超出的用...表示
  rowCut.splice(1, 1, group);
  row = rowCut;
 }
 for (var b = 0; b < row.length; b++) {
  ctx.fillText(row[b], width / 2, height / 2 * 1.15+b*26);
 }
              //ctx.fillText(posterName, width / 2, height / 2 * 1.2);
              ctx.drawImage(qrcodeImg,width / 2 * 0.73, height / 2 * 1.32, width / 2 * 0.5,  width / 2 * 0.5);
              setTimeout(() => {
                that.toSave(canvas, width, height);
              }, 1000);
            }
          },
          fail: (err) => {}
        })
      })
  },

  toSave(canvas, width, height) {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 20,
      width: width,
      height: height,
      destWidth: width * wx.getSystemInfoSync().pixelRatio,
      destHeight: height * wx.getSystemInfoSync().pixelRatio,
      canvasId: 'myCanvas',
      canvas: canvas,
      success(res) {
        var tempFilePath = res.tempFilePath;
        that.setData({
          loadImagePath: tempFilePath,
        });
      }
    })
  },

  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.loadImagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
            } else {
              console.log(111)
            }
          },
          fail: function (res) {
            console.log(res)
          }
        })
      },
      fail(ress){
        wx.openSetting({
          success(rea){
            console.log(rea);
            if (rea.authSetting['scope.writePhotosAlbum']) {
              home.wxMessage('获取权限成功,再次保存图片即可','none');
            }
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getGuestList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})